const rp = require('request-promise-native');

// const { createReadStream } = require('fs');
// const { resolve } = require('path')
// 引入config模块
const {
    appID,
    appsecret,
    template_id,
    touser
} = require('../connfig');
//引入menu模块
const menu = require('./menu');
//引入api模块
const api = require('../utlis/api');

//引入tool
const { writeFileAsync, readFileAsync } = require('../utlis/tool');
const { log } = require('console');


class Wechat {
    constructor() {

    }

    //用来获取access_token
    getAccessToken() {
        const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appID}&secret=${appsecret}`;
        return new Promise((resolve, reject) => {
            rp({
                    method: 'GET',
                    url,
                    json: true
                })
                .then(res => {
                    res.expires_in = Date.now() + (res.expires_in - 300) * 1000;
                    resolve(res)
                })
                .catch(err => {
                    reject('getAccessToken出了问题' + err)
                })
        })

    }
    saveAccessToken(accessToken) {
        return writeFileAsync(accessToken, 'accessToken.txt')
    };
    //用来读取access_token
    readAccessToken() {
        return readFileAsync('accessToken.txt')
    };
    //用来检测access_token是否有效
    isValidAccessToken(data) {
        if (!data && !data.access_token && !data.expires_in) {
            return false;
        }
        return data.expires_in > Date.now();
    };
    //用来获取没有过期的access_token
    fetchAccessToken() {
        if (this.access_token && this.expires_in && this.isValidAccessToken(this)) {
            return Promise.resolve({
                access_token: this.access_token,
                expires_in: this.expires_in
            })
        }
        return this.readAccessToken()
            .then(async res => {
                if (this.isValidAccessToken(res)) {
                    return Promise.resolve(res)
                } else {
                    const res = await this.getAccessToken();
                    await this.saveAccessToken(res);
                    return Promise.resolve(res)
                }
            })
            .catch(async err => {
                const res = await this.getAccessToken();
                await this.saveAccessToken(res);
                return Promise.resolve(res)
            })
            .then(res => {
                this.access_token = res.access_token;
                this.expires_in = res.expires_in;
                return Promise.resolve(res);
            })
    };



    //用来获取jsapi_ticket
    getTicket() {

        return new Promise(async(resolve, reject) => {
            const data = await this.fetchAccessToken()
            const url = `${api.ticket}&access_token=${data.access_token}`;
            rp({
                    method: 'GET',
                    url,
                    json: true
                })
                .then(res => {

                    resolve({
                        ticket: res.ticket,
                        expires_in: Date.now() + (res.expires_in - 300) * 1000
                    })
                })
                .catch(err => {
                    reject('getTicket出了问题' + err)
                })
        })

    };
    //用来保存jsapi_ticket
    saveTicket(ticket) {
        return writeFileAsync(ticket, 'ticket.txt')
    };
    //用来读取jsapi_ticket
    readTicket() {
        return readFileAsync('ticket.txt')
    };
    //用来检测jsapi_ticket是否有效
    isValidTicket(data) {
        if (!data && !data.ticket && !data.expires_in) {
            return false;
        }
        return data.expires_in > Date.now();
    };
    //用来获取没有过期的jsapi_ticket
    fetchTicket() {
        if (this.ticketn && this.ticket_expires_in && this.isValidTicket(this)) {
            return Promise.resolve({
                ticket: this.ticket,
                expires_in: this.expires_in
            })
        }
        return this.readTicket()
            .then(async res => {
                if (this.isValidTicket(res)) {
                    return Promise.resolve(res)
                } else {
                    const res = await this.getTicket();
                    await this.saveTicket(res);
                    return Promise.resolve(res)
                }
            })
            .catch(async err => {
                const res = await this.getTicket();
                await this.saveTicket(res);
                return Promise.resolve(res)
            })
            .then(res => {
                this.ticket = res.ticket;
                this.ticket_expires_in = res.expires_in;
                return Promise.resolve(res);
            })
    };


    getCode() {
        const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appID}&secret=${appsecret}`;
        return new Promise((resolve, reject) => {
            rp({
                    method: 'GET',
                    url,
                    json: true
                })
                .then(res => {
                    res.expires_in = Date.now() + (res.expires_in - 300) * 1000;
                    resolve(res)
                })
                .catch(err => {
                    reject('getAccessToken出了问题' + err)
                })
        })
    };

    //创建菜单
    createMenu(menu) {

        return new Promise(async(resolve, reject) => {
            try {
                const data = await this.fetchAccessToken()
                const url = `https://api.weixin.qq.com/cgi-bin/menu/create?access_token=${data.access_token}`;
                const result = await rp({
                    method: 'POST',
                    url,
                    json: true,
                    body: menu
                });
                resolve(result);
            } catch (e) {
                reject('createMenu方法出了问题' + e);
            }
        })
    };;
    //删除菜单
    deleteMenu() {
        return new Promise(async(resolve, reject) => {
            try {
                const data = await this.fetchAccessToken();
                const url = `https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=${data.access_token}`;
                const result = await rp({
                    method: 'GET',
                    url,
                    json: true
                })
                resolve(result);
            } catch (e) {
                reject('deleteMenu方法出了问题' + e)
            }
        })
    };
    //模块推荐
    // getMokuai() {
    //     const sendDate = {
    //         touser,
    //         template_id,
    //         url: 'http://awkvty.natappfree.cc/detailpage',
    //         data: {
    //             nameData: {
    //                 value: '小贾'
    //             },
    //             dotaData: {
    //                 value: '2023/3/13'
    //             },
    //             beizhu: {
    //                 value: 'nicai'
    //             }
    //         }
    //     }

    //     return new Promise(async(resolve, reject) => {
    //         try {
    //             const data = await this.fetchAccessToken();
    //             const url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${data.access_token}`;
    //             const mokaun = await rp({
    //                 method: 'POST',
    //                 url,
    //                 json: true,
    //                 body: sendDate
    //             });
    //             resolve(mokaun);
    //         } catch (e) {
    //             reject('  getMokuai方法出了问题' + e);
    //         }
    //     })
    // }


    //上传临时素材
    // uploadTemporaryMaterial(type, fileName) {
    //     try {
    //         const filePath = resolve(__dirname, '../media', fileName)
    //         return new Promise(async(resolve, reject) => {
    //             const data = await this.fetchAccessToken();
    //             const url = `${api.temporary.upload}access_token=${data.access_token}&type=${type}`;
    //             const formData = {
    //                 media: createReadStream(filePath)
    //             }
    //             const result = rp({ method: 'post', url, json: true, formData });
    //             resolve(result)
    //         })
    //     } catch (e) {
    //         reject('uploadTemporaryMaterial方法出了问题', +e)
    //     }
    // };
    // //上传永久素材
    // uploadPermaneMaterial(type, material, body) {
    //     const filePath = resolve(__dirname, '../media', fileName);
    //     return new Promise(async(resolve, reject) => {
    //         const data = await this.fetchAccessToken();
    //         const url = `${api.temporary.upload}access_token=${data.access_token}&type=${type}`;
    //         let options = {
    //             method: "post",
    //             json: true
    //         };


    //         if (type === 'news') {
    //             options.url = `${api.permanment.addNews}access_token=${data.access_token}`;

    //         }
    //         rp(options)
    //     })
    // } catch (e) {
    //     reject('uploadPermaneMaterial方法出了问题', +e)
    // }

    // gtejanklfkl() {

    //     return new Promise(async(resolve, reject) => {
    //         const data = await this.fetchAccessToken();
    //         const url = ` https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token=${data.access_token}`;

    //         const result = rp({ method: 'get', url, json: true, });
    //         resolve(result)
    //     })
    // } catch (e) {
    //     reject('uploadPermaneMaterial方法出了问题', +e)
    // }

    //新建草稿
    // newDraft() {


    //     return new Promise(async(resolve, reject) => {
    //         const access_token = await this.fetchAccessToken();
    //         data = {
    //             "articles": [{
    //                     "title": '慢阻肺预防',
    //                     "author": '贝莱福',
    //                     "digest": '',
    //                     "content": CONTENT,
    //                     "content_source_url": CONTENT_SOURCE_URL,
    //                     "thumb_media_id": THUMB_MEDIA_ID,
    //                     "need_open_comment": 0,
    //                     "only_fans_can_comment": 0
    //                 }
    //                 //若新增的是多图文素材，则此处应还有几段articles结构
    //             ]
    //         }
    //         const url = `https://api.weixin.qq.com/cgi-bin/draft/add?access_token=${access_token}`;
    //         rp({
    //                 method: 'POST',
    //                 url,
    //                 json: true
    //             })
    //             .then(res => {
    //                 resolve(res)
    //             })
    //             .catch(err => {
    //                 reject('newDraft出了问题' + err)
    //             })
    //     })
    // }

}


// 模拟测试

(async() => {
    const w = new Wechat();
    let result = await w.deleteMenu();
    //创建新的菜单
    result = await w.createMenu(menu);
    // w.fetchTicket();
    // const data = await w.fetchAccessToken();
})()

module.exports = Wechat;